from rest_framework.authentication import BaseAuthentication
from django.core.cache import cache

from users.models import UserModel
from utils.errors import ParamsException


class UserAuthentication(BaseAuthentication):

    def authenticate(self, request):
        # 判断当前请求地址为登录和注册时，返回None
        not_path = ['/api/user/auth/register/', '/api/user/auth/login/']
        for path in not_path:
            if request.path == path:
                return None
        # 该方法必须被重写
        token = request.query_params.get('token')\
            if request.query_params.get('token')\
            else request.data.get('token')
        if not token:
            raise ParamsException({'code': 1006, 'msg': '用户认证失败，请去登录'})
        user_id = cache.get(token)
        if not user_id:
            raise ParamsException({'code': 1006, 'msg': '用户认证失败，请去登录'})
        user = UserModel.objects.filter(pk=user_id).first()
        # return user, token   相当于request.user=user
        #                           request.token=token
        return user, token

